<template>
  <ul
    class="segmented"
    :style="{
      width: props.block ? '100%' : 'auto'
    }"
  >
    <li
      class="segmented-item"
      v-for="(opt, index) in list"
      :key="index"
      :class="{
        'segmented-item-small': props.size === SegmentedSizeEnum.small,
        'segmented-item-large': props.size === SegmentedSizeEnum.large,
        'segmented-item-select-primary':
          props.value === opt.value && props.type === SegmentedTypeEnum.primary,
        'segmented-item-select-success':
          props.value === opt.value && props.type === SegmentedTypeEnum.success,
        'segmented-item-select-warning':
          props.value === opt.value && props.type === SegmentedTypeEnum.warning,
        'segmented-item-select-info':
          props.value === opt.value && props.type === SegmentedTypeEnum.info,
        'segmented-item-select-danger':
          props.value === opt.value && props.type === SegmentedTypeEnum.danger,

        'segmented-item-primary': props.type === SegmentedTypeEnum.primary,
        'segmented-item-success': props.type === SegmentedTypeEnum.success,
        'segmented-item-warning': props.type === SegmentedTypeEnum.warning,
        'segmented-item-info': props.type === SegmentedTypeEnum.info,
        'segmented-item-danger': props.type === SegmentedTypeEnum.danger,
        'is-plain': props.plain,
        'is-disabled': opt.disabled
      }"
      @click="selectOpt(opt)"
    >
      <slot name="opt" :data="opt">
        {{ opt.label }}
      </slot>
    </li>
  </ul>
</template>

<script setup lang="ts">
import { SegmentedProps } from '../../props'
import type { SegmentedOption } from '../../types'
import { SegmentedSizeEnum, SegmentedTypeEnum } from '../../enums'

const props = defineProps(SegmentedProps)
const emit = defineEmits(['update:value', 'change'])

const selectOpt = (opt: SegmentedOption) => {
  if (!opt.disabled) {
    emit('update:value', opt.value)
    emit('change', opt.value, opt)
  }
}

const selectItemByIndex = (index: number) => {
  const opt = props.list[index]
  if (opt && !opt.disabled) {
    emit('update:value', opt.value)
    emit('change', opt.value, opt)
  }
}

const selectItemByKey = (key: keyof SegmentedOption, val: any) => {
  const opt = props.list.find((item) => {
    return item[key] === val
  })
  if (opt && !opt.disabled) {
    emit('update:value', opt.value)
    emit('change', opt.value, opt)
  }
}

const selectItemByValue = (value: string) => {
  selectItemByKey('value', value)
}

const selectItemByLabel = (label: string) => {
  selectItemByKey('label', label)
}

defineExpose({
  selectItemByIndex,
  selectItemByKey,
  selectItemByValue,
  selectItemByLabel
})
</script>

<style lang="scss" scoped>
@import './Segmented.scss';
</style>
